<?php

class PostAction extends AdminbaseAction {

	protected $posts_obj;

	protected $terms_relationship;

	protected $terms_obj;

	function _initialize() {

		parent::_initialize();

		$this->posts_obj = new PostsModel();

		$this->terms_obj = new TermsModel();

		$this->terms_relationship=new TermRelationshipsModel();

	}

	/**

	 * 文章管理首页

	 * @return [type] [description]

	 */

	function index(){

		$this->_lists();

		$this->_getTree();

		$this->display();

	}


	function add(){

		$this->_getTree();

		// $terms_obj = new TermsModel();

		// $term_id = (int) $this->_get("term");

		// echo $term_id;

		// $term = $terms_obj->where("term_id=$term_id")->find();

		// $this->assign("author","1");

		// $this->assign("term",$term);

		// print_r($term);

		$this->display();

	}

	

	function add_post(){

		$this->_getTree();



		// $terms_obj = new TermsModel();

	

		if (IS_POST) {

			// 关键词替换
			$post_list = M('posts')->field('ID as id , inner_keyword as name, view as click')->where("inner_keyword <> ''")->select();
			foreach ($post_list as $key => $value) {
				$post_list[$key]['type'] = 'post';
			}

			$term_list = M('terms')->field('term_id as id , name , count as click')->select();
			foreach ($term_list as $key => $value) {
				$term_list[$key]['type'] = 'term';
			}

			$list = M('inner_keyword')->select();

			$list = array_merge($list,array_merge($term_list,$post_list));

			// $_POST['post']['post_content'] 
			// p($list);

			// foreach ($list as $key => $value) {
			// 	if(!empty($value['type']) && $value['type'] == 'term'){
			// 		$replace = '<a href="'.U('/list/'.$value['id']).'" title="'.$value['name'].'">'.$value['name'].'</a>';
			// 	}elseif(!empty($value['type']) && $value['type'] == 'post'){
			// 		$replace = '<a href="'.U('/article/'.$value['id']).'" title="'.$value['name'].'">'.$value['name'].'</a>';
			// 	}else{
			// 		$replace = '<a href="'.$value['url'].'" title="'.$value['name'].'">'.$value['name'].'</a>';
			// 	}
			// 	$_POST['post']['post_content'] = str_replace($value['name'], $replace, $_POST['post']['post_content']);
			// 	$_POST['post']['product_info']['detail'] = str_replace($value['name'], $replace, $_POST['post']['product_info']['detail']);
			// 	$_POST['post']['product_info']['customer'] = str_replace($value['name'], $replace, $_POST['post']['product_info']['customer']);
			// 	foreach ($_POST['post']['xijie']['name'] as $k => $v) {
			// 		$_POST['post']['xijie']['name'][$k] = str_replace($value['name'], $replace, $_POST['post']['xijie']['name'][$k]);
			// 		$_POST['post']['xijie']['content'][$k] = str_replace($value['name'], $replace, $_POST['post']['xijie']['content'][$k]);
			// 		$_POST['post']['shijing']['name'][$k] = str_replace($value['name'], $replace, $_POST['post']['shijing']['name'][$k]);
			// 		$_POST['post']['shijing']['cp'][$k] = str_replace($value['name'], $replace, $_POST['post']['shijing']['cp'][$k]);
			// 	}
			// }

			// 产品部分
			// $_POST['post']['product_info'] = json_encode($_POST['post']['product_info']);
			// $_POST['post']['xijie'] = json_encode($_POST['post']['xijie']);
			// $_POST['post']['shijing'] = json_encode($_POST['post']['shijing']);
			$_POST['post']['para'] = json_encode($_POST['post']['para']);
			// pe($_POST['post']['para']);
			if(!empty($_POST['photos_alt']) && !empty($_POST['photos_url'])){

				foreach ($_POST['photos_url'] as $key => $url){

					// $photourl=substr($url, strlen(C("TMPL_PARSE_STRING.__UPLOAD__")));

					$_POST['smeta']['photo'][] = array("url"=>$url,"alt"=>$_POST['photos_alt'][$key]);

				}

			}

			// print_r($_POST['smeta']['photo']);

			// echo $_POST['smeta']['thumb'].'|';

			// echo strlen(C("TMPL_PARSE_STRING.__UPLOAD__")).'|';

			// $cloud_config = include 'data/conf/cloud.php';

			// if(! $cloud_config['status'])

				// $_POST['smeta']['thumb'] = substr($_POST['smeta']['thumb'], strlen(C("TMPL_PARSE_STRING.__UPLOAD__")));

			// exit;

			$_POST['post']['term_id']       = $_POST['term']['term_id'];

			$_POST['post']['create_time']   = time();

			$_POST['post']['post_date'] 	= date("Y-m-d H:i:s",time());

			$_POST['post']['smeta'] 		= json_encode($_POST['smeta']);

			$_POST['post']['post_author'] 	= get_current_admin_id();

			// print_r($_POST);exit;

			$result = $this->posts_obj->add($_POST['post']);

			if ($result) {

				//

				// $_POST['term']['object_id'] = $result;

				// $result = $this->terms_relationship->add($_POST['term']);

				// if ($result) {

				// 	$this->success("新增成功！");

				// }else{

				// 	$this->error("归类失败！");

				// }

				$this->success('新增成功');

			} else {

				$this->error("新增失败！");

			}

			 

		}

	}

	

	/**

	 * 已经修改 414、2201

	 * @return [type] [description]

	 */

	public function edit(){

		$this->_getTree();

		$id = (int) $this->_get("id");

		$post = $this->posts_obj->where("ID = $id")->find();

        $post['product_info'] = json_decode($post['product_info'],1);
        $post['xijie'] = json_decode($post['xijie'],1);
        $post['shijing'] = json_decode($post['shijing'],1);

		$this->assign("post",$post);

		$this->assign("smeta",json_decode($post['smeta'],true));

		// 栏目信息
		$term = M('terms')->where("term_id = ".$post['term_id'])->find();

		$this->assign("term",$term);
		$this->term_id = $post['term_id'];
		$this->id = $id;
		
		$this->display();

	}



	/**

	 * 修改文章

	 * @return [type] [description]

	 */

	public function edit_post(){

		$terms_obj = new TermsModel();

		if (IS_POST) {

			// $_POST['post']['product_info'] = json_encode($_POST['post']['product_info']);
			// $_POST['post']['xijie'] = json_encode($_POST['post']['xijie']);
			// $_POST['post']['shijing'] = json_encode($_POST['post']['shijing']);
			$_POST['post']['para'] = json_encode($_POST['post']['para']);
			
			// print_r($_POST);exit;

			if(!empty($_POST['photos_alt']) && !empty($_POST['photos_url'])){

				foreach ($_POST['photos_url'] as $key=>$url){

					// $photourl=substr($url, strlen(C("TMPL_PARSE_STRING.__UPLOAD__")));

					$_POST['smeta']['photo'][] = array("url"=>$url,"alt"=>$_POST['photos_alt'][$key]);

				}

			}

			// $_POST['smeta']['thumb'] = str_replace(C("TMPL_PARSE_STRING.__UPLOAD__"),'',$_POST['smeta']['thumb']);

			// 

			// $_POST['post']['term_id'] = $_POST['term']['term_id'];

			$_POST['post']['smeta'] = json_encode($_POST['smeta']);
			$_POST['post']['create_time'] = strtotime($_POST['post']['post_modified']);
			$_POST['post']['post_date'] = $_POST['post']['post_modified'];


			unset($_POST['post']['post_author']);

			// pe($_POST);

			$result = $this->posts_obj->save($_POST['post']);

			//echo($this->posts_obj->getLastSql());die;

			if ($result!==false) {

				$this->success("保存成功！");

			} else {

				$this->error("保存失败！");

			}

		}

	}

	

	/**

	 * 排序

	 * @return [type] [description]

	 */

	public function listorders() {

// Array

// (

//     [listorders] => Array

//         (

//             [31] => 0

//             [32] => 1

//         )



// )

		foreach ($_POST['listorders'] as $id => $order) {

			$status = M('posts')->where('ID='.$id)->setField('listorder',$order);

		}

		// print_r($_POST);exit;

		// $status = parent::listorders($this->terms_relationship);

		if ($status) {

			$this->success("排序更新成功！");

		} else {

			$this->error("排序更新失败！");

		}

	}

	/**

	 * 获取文章列表

	 * status 0 为删除

	 * @param  integer $status [description]

	 * @return [type]          [description]

	 */

	private  function _lists($status = 1){

		$terms_obj= new TermsModel();

		// 获取搜索

		$term_id = intval($_REQUEST["term"]);

		$term = $terms_obj->where("term_id=$term_id")->find();

		$this->assign("term",$term);

		// print_r($term);

		// $where_ands = empty($term_id)?array("a.status=$status"):array("a.term_id = $term_id and a.status=$status");

		$where_ands = empty($term_id)?array("status = $status and post_type IS NULL"):array("term_id = $term_id and status = $status and post_type IS NULL");



		$_GET['term'] = $_REQUEST['term'];



		$fields=array(

				'start_time'=> array("field"=>"post_date","operator"=>">"),

				'end_time'  => array("field"=>"post_date","operator"=>"<"),

				'keyword'  => array("field"=>"post_title","operator"=>"like"),

		);

		if(IS_POST){

			

			foreach ($fields as $param => $val){

				if (isset($_POST[$param]) && !empty($_POST[$param])) {

					$operator = $val['operator'];

					$field    = $val['field'];

					$get 	  = $_POST[$param];

					$_GET[$param] = $get;

					if($operator=="like"){

						$get = "%$get%";

					}

					array_push($where_ands, "$field $operator '$get'");

				}

			}

		}else{

			foreach ($fields as $param =>$val){

				if (isset($_GET[$param]) && !empty($_GET[$param])) {

					$operator=$val['operator'];

					$field   =$val['field'];

					$get=$_GET[$param];

					if($operator=="like"){

						$get="%$get%";

					}

					array_push($where_ands, "$field $operator '$get'");

				}

			}

		}

		

		$where= join(" and ", $where_ands);

		

		// echo $where;

		$count = M('posts')

			->where($where)

			->count();



		// echo $count;



		$page = $this->page($count, 20);

			

		$posts = M('posts')

			->where($where)

			->limit($page->firstRow . ',' . $page->listRows)

			->order("listorder ASC")

			->select();

			

		foreach ($posts as $key => $value) {

			$posts[$key]['term_name'] = M('terms')->where('term_id='.$value['term_id'])->getField('name');

		}



		// pe($posts);



		$users_obj = new UsersModel();

		$users_data = $users_obj->field("ID,user_login")->where("user_status=1")->select();

		$users=array();

		foreach ($users_data as $u){

			$users[$u['ID']]=$u;

		}

		$this->assign("users",$users);

		$this->assign("Page", $page->show('Admin'));

		$this->assign("current_page",$page->GetCurrentPage());

		unset($_GET[C('VAR_URL_PARAMS')]);

		$this->assign("formget",$_GET);

		$this->assign("posts",$posts);

	}

	

	private function _getTree(){

		$term_id=$_REQUEST['term'];

		$result = $this->terms_obj->order(array("listorder"=>"asc"))->select();

		

		$tree = new Tree();

		$tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');

		$tree->nbsp = '&nbsp;&nbsp;&nbsp;';

		foreach ($result as $r) {

			$r['str_manage'] = '<a href="' . U("term/add", array("parent" => $r['term_id'])) . '">添加子类</a> | <a href="' . U("term/edit", array("id" => $r['term_id'])) . '">修改</a> | <a class="J_ajax_del" href="' . U("term/delete", array("id" => $r['term_id'])) . '">删除</a> ';

			$r['visit'] = "<a href='#'>访问</a>";

			$r['taxonomys'] = $this->taxonomys[$r['taxonomy']];

			$r['id']=$r['term_id'];

			$r['parentid']=$r['parent'];

			$r['selected']=$term_id==$r['term_id']?"selected":"";

			$array[] = $r;

		}

		

		$tree->init($array);

		$str="<option value='\$id' \$selected>\$spacer\$name</option>";

		$taxonomys = $tree->get_tree(0, $str);

		$this->assign("taxonomys", $taxonomys);

	}

	

	/**

	 * 删除文章

	 * 单一删除 和 批量删除

	 * @return [type] [description]

	 */

	function delete(){

		if(isset($_GET['id'])){

			$id = (int) $_GET['id'];

			if(M('posts')->where('ID='.$id)->setField('status',0)){

				$this->success('删除成功');

			}else{

				$this->error('删除失败');

			}

		}

		if(isset($_POST['ids'])){

			$ids = implode(',', $_POST['ids']);

			if(M('posts')->where("ID in ($ids)")->setField('status',0)){

				$this->success('批量删除成功');

			}else{

				$this->error('批量删除失败');

			}

		}

		// if(isset($_GET['tid'])){

		// 	$tid = (int) $this->_get("tid");

		// 	$data['status']=0;

		// 	if ($this->terms_relationship->where("tid=$tid")->save($data)) {

		// 		$this->success("删除成功！");

		// 	} else {

		// 		$this->error("删除失败！");

		// 	}

		// }

		// if(isset($_POST['ids'])){

		// 	$tids=join(",",$_POST['ids']);

		// 	$data['status']=0;

		// 	if ($this->terms_relationship->where("tid in ($tids)")->save($data)) {

		// 		$this->success("删除成功！");

		// 	} else {

		// 		$this->error("删除失败！");

		// 	}

		// }

	}

	

	function check(){

		if(isset($_POST['ids']) && $_GET["check"]){

			$data["post_status"]=1;

			

			$tids=join(",",$_POST['ids']);

			$objectids=$this->terms_relationship->field("object_id")->where("tid in ($tids)")->select();

			$IDs=array();

			foreach ($objectids as $id){

				$IDs[]=$id["object_id"];

			}

			$IDs=join(",", $IDs);

			if ( $this->posts_obj->where("ID in ($IDs)")->save($data)) {

				$this->success("取消审核成功！");

			} else {

				$this->error("取消审核失败！");

			}

		}

		if(isset($_POST['ids']) && $_GET["uncheck"]){

			

			$data["post_status"]=0;

			$tids=join(",",$_POST['ids']);

			$objectids=$this->terms_relationship->field("object_id")->where("tid in ($tids)")->select();

			$IDs=array();

			foreach ($objectids as $id){

				$IDs[]=$id["object_id"];

			}

			$IDs=join(",", $IDs);

			if ( $this->posts_obj->where("ID in ($IDs)")->save($data)) {

				$this->success("取消审核成功！");

			} else {

				$this->error("取消审核失败！");

			}

		}

	}

	

	

	function move(){

		if(IS_POST){

			if(isset($_GET['ids']) && isset($_POST['term_id'])){

				$ids = $_GET['ids'];

				// $tids = $_GET['ids'];

				// print_r($_POST);

				// print_r($_GET);exit;

				$term_id = $_POST['term_id'];

				if ( M('posts')->where("ID in ($ids)")->setField('term_id',$term_id)) {

					$this->success("移动成功！");

				} else {

					$this->error("移动失败！");

				}

				// if ( $this->terms_relationship->where("tid in ($tids)")->save($_POST)) {

				// 	$this->success("移动成功！");

				// } else {

				// 	$this->error("移动失败！");

				// }

			}

		}else{

			$terms_obj=new TermsModel();

			$parentid = (int) $this->_get("parent");

			$tree = new PathTree();

			$tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');

			$tree->nbsp = '---';

			$result =$terms_obj->order(array("path"=>"asc"))->select();

			$tree->init($result);

			$tree=$tree->get_tree();

			$this->assign("terms",$tree);

			

			$this->display();

		}

	}

	/**

	 * 回收站首页

	 * @return [type] [description]

	 */

	function recyclebin(){

		$this->_lists(0);

		$this->_getTree();

		$this->display();

	}

	

	/**

	 * 彻底删除文章

	 * @return [type] [description]

	 */

	function clean(){

		if(isset($_GET['id'])){

			$id = (int) $_GET['id'];

			if (M('posts')->where('ID='.$id)->delete()) {

				$this->success("彻底删除成功！");

			} else {

				$this->error("彻底删除失败！");

			}

		}

		if(isset($_POST['ids'])){

			$ids = implode(',', $_POST['ids']);

			if(M('posts')->where("ID in ($ids)")->delete()){

				$this->success('批量彻底删除成功');

			}else{

				$this->error('批量彻底删除失败');

			}

		}

		// if(isset($_POST['ids'])){

		// 	$ids = implode(",", $_POST['ids']);

		// 	$tids= implode(",", array_keys($_POST['ids']));

		// 	$data=array("post_status"=>"0");

		// 	$status=$this->terms_relationship->where("tid in ($tids)")->delete();

		// 	if($status){

		// 		$status=$this->posts_obj->where("ID in ($ids)")->delete();

		// 	}

			

		// 	if ($status) {

		// 		$this->success("删除成功！");

		// 	} else {

		// 		$this->error("删除失败！");

		// 	}

		// }else{

		// 	if(isset($_GET['id'])){

		// 		$id = (int) $this->_get("id");

		// 		$tid = (int) $this->_get("tid");

		// 		$status=$this->terms_relationship->where("tid = $tid")->delete();

		// 		if($status){

		// 			$status=$this->posts_obj->where("ID=$id")->delete();

		// 		}

		// 		if ($status) {

		// 			$this->success("删除成功！");

		// 		} else {

		// 			$this->error("删除失败！");

		// 		}

		// 	}

		// }

	}

	

	/**

	 * 还原文章

	 * @return [type] [description]

	 */

	function restore(){

		if(isset($_GET['id'])){

			$id = (int) $_GET['id'];

			if( M('posts')->where('ID='.$id)->setField('status',1) ){

				$this->success('还原成功');

			}else{

				$this->error('还原失败');

			}

		}

		// if(isset($_GET['id'])){

		// 	$id = (int) $this->_get("id");

		// 	$data=array("tid"=>$id,"status"=>"1");

		// 	if ($this->terms_relationship->save($data)) {

		// 		$this->success("还原成功！");

		// 	} else {

		// 		$this->error("还原失败！");

		// 	}

		// }

		

	}

	

	

	

}